package com.xzl.time.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.xzl.time.config.ApplicationContextProvider;
import com.xzl.time.mapper.NoticeMapper;
import com.xzl.time.netty.MyWebSocketHandler;
import com.xzl.time.pojo.Notice;
import com.xzl.tool.util.RespBean;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

import java.nio.charset.Charset;
import java.util.HashMap;

@Slf4j
public class SysNoticeListener implements ChannelAwareMessageListener {

    private static ObjectMapper MAPPER = new ObjectMapper();

    //从spring容器中获取noticeMapper
    NoticeMapper noticeMapper =
            ApplicationContextProvider
                    .getApplicationContext()
                    .getBean(NoticeMapper.class);
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        //获取用户id，可以通过队列名称获取
        String queueName = message.getMessageProperties().getConsumerQueue();
        String userId = queueName.substring(queueName.lastIndexOf("_") + 1);
        log.info("SysNoticeListener => "+userId);
        //获取当前用户的websocket连接
        io.netty.channel.Channel wsChannel = MyWebSocketHandler.userChannelMap.get(userId);

        //封装消息数据数据
        String msg = new String(message.getBody(), Charset.defaultCharset());
        JSONObject jsonObject = JSON.parseObject(msg);
        Notice notice = JSONObject.toJavaObject(jsonObject, Notice.class);
        notice.setReceiverId(userId);
        //判断是否有消息
        if (notice != null && StringUtils.isNotBlank(notice.getAction())){
            int i = Integer.parseInt(notice.getAction());
            //添加消息数据
            if (i == 1) noticeMapper.insert(notice);
                //删除消息数据
            else noticeMapper.delNoticeById(notice);
        }
        //判断用户是否在线
        if (wsChannel != null) {
            //如果连接不为空，表示用户在线
            //封装返回数据
            HashMap countMap = new HashMap();
            countMap.put("sysNoticeCount", 1);
            countMap.put("notice",msg);
            RespBean result = RespBean.success("查询成功", countMap);

            // 把数据通过WebSocket连接主动推送用户
            wsChannel.writeAndFlush(new TextWebSocketFrame(MAPPER.writeValueAsString(result)));
        }
    }
}
